package property.service.impl;

import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import property.mapper.FinanceMapper;
import property.pojo.Finance;
import property.service.FinanceService;
import property.utils.mapper.MyBatisUtil;

public class FinanceServiceImpl implements FinanceService {
    @Override
    public int financeInsert(Finance finance) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        FinanceMapper mapper = sqlSession.getMapper(FinanceMapper.class);
        int i = 0;
        try {
            i = mapper.insertSelective(finance);
        }catch (Exception e){
            if (e.getMessage().toString().contains("PRIMARY") || e.getMessage().toString().contains("FOREIGN KEY")) {
                i = -2;
            }
        }
        sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public int updateFinance(Finance finance) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        FinanceMapper mapper = sqlSession.getMapper(FinanceMapper.class);
        int i;
        try {
            i = mapper.updateByPrimaryKeySelective(finance);
        } catch (PersistenceException e){
            i = -1;
        }
        sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public int deleteFinance(Integer id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        FinanceMapper mapper = sqlSession.getMapper(FinanceMapper.class);
        int i;
        try {
            i = mapper.deleteByPrimaryKey(id);
        }catch (PersistenceException e){
            i = -1;
        }
        sqlSession.commit();
        sqlSession.close();
        return i;
    }
}
